import pygame
import sys

from pygame.sprite import DirtySprite, LayeredDirty
from highscore_scene import HighscoreScene
from game_scene import GameScene

from state_manager import *
from settings_manager import *
from button import *
from events import *

path = "data/textures/"

class MenuScene:
	def __init__(self, screen):
		self.screen = screen

	def create(self):
		self.background = pygame.image.load(path + str(SettingsManager.settings.resolution[0]) + "_mainmenu_background.jpg")
		
		self.bNewGame = Button(path + "start1.png", path + "start2.png", path + "start3.png")
		self.bHighScore = Button(path + "scores1.png", path + "scores2.png", path + "scores3.png")
		self.bSettings = Button(path + "settings1.png", path + "settings2.png", path + "settings3.png")
		self.bExit = Button(path + "exit1.png", path + "exit2.png", path + "exit3.png")

		#Set buttons in place
		width, height = self.screen.get_rect().width, self.screen.get_rect().height
		bWidth, bHeight = self.bNewGame.rect.width, self.bNewGame.rect.height
		space = 30

		posX, posY = (width - bWidth) / 2, (height - bHeight * 4 - space * 3) / 2

		self.bNewGame.rect.x = posX
		self.bNewGame.rect.y = posY

		posY += bHeight + space
		self.bHighScore.rect.x = posX
		self.bHighScore.rect.y = posY

		posY += bHeight + space
		self.bSettings.rect.x = posX
		self.bSettings.rect.y = posY

		posY +=  bHeight + space
		self.bExit.rect.x = posX
		self.bExit.rect.y = posY

		#Merge all buttons into a group
		self.group = LayeredDirty()
		self.group.add(self.bNewGame, self.bHighScore, self.bSettings, self.bExit)

	def update(self):
		if StateManager.state.window != StateConst.MainMenu:
			return None #Escape menu updating

		self.manageButtonsClicks()

		self.drawMainMenu()

	def manageButtonsClicks(self):
		if self.bExit.isClicked():
			self.exitGame()
		if self.bSettings.isClicked():
			StateManager.changeWindow(StateConst.Settings)
			StateManager.changeSound(StateConst.SettingsSound)
		if self.bHighScore.isClicked():
			StateManager.changeWindow(StateConst.Highscore)
			StateManager.changeSound(StateConst.HighscoreSound)
		if self.bNewGame.isClicked():
			GameScene.refresh = True
			StateManager.changeWindow(StateConst.Game)
			StateManager.changeSound(StateConst.GameSound)
		
	def drawMainMenu(self):
		self.group.clear(self.screen, self.background)
		update_area = self.group.draw(self.screen)
		pygame.display.update(update_area)
		self.group.update()

	def exitGame(self):
		sys.exit()